//
//  OAuthViewController.swift
//  HJWeibo
//
//  Created by mac on 16/1/13.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking



class OAuthViewController: UIViewController {
    
    //属性的webView
    let webView = UIWebView()
    
    //MARK:关闭页面
    @objc private func close() {
        //dismiss 页面
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //测试 （账号密码自动填充）
    @objc private func myTest() {
        let jsStr = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'oyonomg'"
        //执行js 代码
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
        
    }
    
    
    override func loadView() {
        //将根视图替换为 webView
        view = webView
        //设置代理
        webView.delegate = self
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        //文字渲染颜色
        //只针对当前的导航视图控制器有效
        //navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
        //一经设置 全局有效
//        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
        //设置导航条
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
        

    }
    
    private func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "我的测试", style: .Plain, target: self, action: "myTest")
        
        
    }
    
    //MARK: 加载授权页面
    private func loadOAuthPage() {
        //1.获取url
//        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "1957664129" + "&redirect_uri=" + "http://www.itcast.cn"
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        //可选的url
        let url = NSURL(string: urlString)!
        //获取request
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
        
    }
    
    
}

//swift中， 是将一类的协议方法，写在一起，这样更加好阅读和维护
//同一类的协议方法，就被放在一个扩展中
extension OAuthViewController: UIWebViewDelegate {
    //显示 用户等待指示器
    //代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        //显示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    //非常重要的协议方法
    //通常协议方法 返回值为 bool类型  返回true 通常控件可以正常运行
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //print(request.URL)
        //absoluteString:字符串形式
        //print(request.URL?.absoluteString)
        //截取 url中 code授权码
        guard let urlString = request.URL?.absoluteString else {
            //无法获取 url的字符串 就直接不加载网页
            return false
        }
        
        //字符串的包含
        if urlString.containsString("code=") {
            
          //  print(urlString)
            //将url 中的参数获取到
            guard let query = request.URL?.query else {
                //无法获取到query就直接 不加载网页
                return false
            }
            //print(query)
            let codeStr = "code="
            //将 query 转换成NSString  再截取字符串subString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print(code,query)
            
            //调用 获取token 的方法
            loadAccessToken(code)
            //不希望授权页面跳转到  回调页面
            
            return false
         }
        
        
        return true
    }
    
    
    private func loadAccessToken(code:String) {
        
        //请求token 和用户信息
        HJUserAccountViewModel().loadAccessToken(code) {
            (isSuccess) -> () in
            if !isSuccess {
                print("用户登录失败")
                //HUD 提示用户 登录失败
                SVProgressHUD.showErrorWithStatus("网络君正忙")
                
                return
            }
            //一定登录成功
            SVProgressHUD.showSuccessWithStatus("登录成功")
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                //通知是同步的
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVC, object: "welcome")
                print("welcome")
                
            })
            //切换根视图  但不推荐这样写(违反单一性原则)   可以用通知实现
//            UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
//            
        }
        
        
    }
    
    
    
    /*
    //获取授权的token
    private func loadAccessToken(code:String) {
        
        //url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //参数
        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        //设置支持解析纯文本的json 格式的数据
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print(result)
            //类型转换 将 AnyObject对象 转换为 [Key : Value]
            guard let dict = result as? [String :AnyObject] else {
                print("数据格式不合法")
                return
            }
            
            //程序走到这里 代表 AnyObject 一定被转换为 字典格式的数据
//            let access_token = dict["access_token"] as! String
//            let uid = dict["uid"] as! String
            let account = HJUserAccount(dict:dict)
            print(account)
        
            
            //获取用户信息
            self.loadUserInfo(account)
            
            }) { (_, error) -> Void in
                print(error)
        }
        
    }
    
    //MARK: 加载用户信息
//    private func loadUserInfo(access_token: String,uid: String) {
    private func loadUserInfo(account: HJUserAccount) {
    
        //print(access_token,uid)
        //1.准备url
       let urlString = "https://api.weibo.com/2/users/show.json"
//        let parameters = ["access_token":access_token,"uid":uid]
        
        //OC {"nullObject":[NSNull null]}
        //程序员保证这个地方一定有值
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        
        
        //2.获取AFN对象
        let AFN = AFHTTPSessionManager()
        
        //3.调用 GET方法
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            //获取用户信息数据
            //类型 转换 将 AnyObject对象 转换为 [Key:Value]
            guard let dict = result as? [String : AnyObject] else {
                print("数据格式不合法")
                return
            }
            
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            
            //我们需要的用户信息就全部获取到
            account.name = name
            account.avatar_large = avatar_large
            print(account)
            //保存信息
            account.saveAccount()
            
            
            
            }) { (_, error) -> Void in
                print(error)
        }
       
    }*/
   
}








